﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using dietyuk_wp.Resources;
using Newtonsoft.Json;
using System.IO;
using System.Diagnostics;
using System.Collections.ObjectModel;

namespace dietyuk_wp
{
    public partial class MainPage : PhoneApplicationPage
    {
        private ObservableCollection<FoodSummary> filteredFoodSummaries = new ObservableCollection<FoodSummary>();
        private static int MAX_FOOD_SUMMARIES = 25;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            using (var rs = Application.GetResourceStream(new Uri("data/usda.idx.json", UriKind.Relative)).Stream)
            {
                using (var sr = new StreamReader(rs))
                {
                    var usdaIdxJson = sr.ReadToEnd();
                    App.foodSummaries = JsonConvert.DeserializeObject<List<FoodSummary>>(usdaIdxJson);
                    Debug.WriteLine("USDA contains {0} foods", App.foodSummaries.Count);
                    this.DataContext = filteredFoodSummaries;
                }
            }
            filterFoods();
        }

        private void filterFoods()
        {
            filteredFoodSummaries.Clear();
            var lowerSearch = searchBox.Text.ToLower();
            foreach (var foodSummary in App.foodSummaries) {
                if (foodSummary.i.ToLower().Contains(lowerSearch) || foodSummary.n.ToLower().Contains(lowerSearch))
                {
                    filteredFoodSummaries.Add(foodSummary);
                }
                if (filteredFoodSummaries.Count >= MAX_FOOD_SUMMARIES)
                {
                    break;
                }
            }
        }

        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}

        private void searchBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            filterFoods();
        }

        private void LongListSelector_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FoodSummary foodSummary = (FoodSummary) foodSelector.SelectedItem;
            Debug.WriteLine("Tap: {0}", foodSelector.SelectedItem);
            var page = new FoodShowPage();
            NavigationService.Navigate(new Uri("/FoodShowPage.xaml?foodNdb=" + foodSummary.o, UriKind.Relative));
        }

        private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Debug.WriteLine("Selection Changed: {0}", e.AddedItems[0]);
        }
    }
}